import json
import pickle
from functools import lru_cache
from pathlib import Path
from openai import OpenAI

client: OpenAI

# 缓存文件路径
CACHE_FILE = 'translation_cache.pkl'
cache: dict


def load_cache():
    """从文件中加载缓存"""
    if Path(CACHE_FILE).exists():
        with open(CACHE_FILE, 'rb') as f:
            return pickle.load(f)
    return {}

def save_cache(f_cache):
    """将缓存保存到文件中"""
    with open(CACHE_FILE, 'wb') as f:
        pickle.dump(f_cache, f)


def contains_chinese(text):
    """
    判断字符串中是否包含中文或中文标点符号
    """
    for char in text:
        # 检查是否为中文字符或中文标点
        if '\u4e00' <= char <= '\u9fff' or '\u3000' <= char <= '\u303f' or '\uff00' <= char <= '\uffef':
            return True
    return False


def translate(text, is_big):
    if text is None or text == "" or text.isspace():
        return ""
    global client
    msg = (f'把{{}}里的内容翻译成英文，这是{is_big}'
           f'（注意：1.只要输出译文！2.译文不要包含包裹大括号！3.不要输出除译文外的任何内容或提示！！！4.如果原文是随机的无意义的中文，译文则“abcabcabc”即可！）')
    print(text)
    try:
        completion = client.chat.completions.create(
            model="qwen-turbo",
            messages=[
                {'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': f'{msg}：\n{{{text}}}'}
            ],
        )
        print(completion.choices[0].message.content)
        print('\n-------------\n')
        return completion.choices[0].message.content
    except Exception as e:
        print(e)
        return None

@lru_cache(maxsize=None)
def translate_text(text, is_big):
    global cache
    """
    翻译文本的函数，留空供你实现
    :param is_big: 1
    :param text: 需要翻译的文本
    :return: 翻译后的文本
    """
    if not contains_chinese(text):
        return text
    # 检查缓存
    cache_key = (text, is_big)
    if cache_key in cache and cache[cache_key]:
        return cache[cache_key]

    # 调用翻译函数
    translated_text = translate(text, is_big)

    # 更新缓存
    cache[cache_key] = translated_text

    return translated_text


def translate_response(d):
    desc = 'api的一个response的example的一个字段值'
    if isinstance(d, dict):
        for key, value in d.items():
            if isinstance(value, str):
                d[key] = translate_text(value, desc)
            elif isinstance(value, (dict, list)):
                translate_response(value)
    elif isinstance(d, list):
        for i, item in enumerate(d):
            if isinstance(item, str):
                d[i] = translate_text(item,desc)
            elif isinstance(item, (dict, list)):
                translate_response(item)


def translate_titles(data):
    desc = 'api的一个参数的描述'
    if isinstance(data, dict):
        for key, value in data.items():
            if key == "title" and isinstance(value, str):
                data[key] = translate_text(value, desc)
            else:
                translate_titles(value)
    elif isinstance(data, list):
        for item in data:
            translate_titles(item)


def translate_openapi(json_data):
    """
    翻译OpenAPI 3.0.1 JSON数据中的指定字段
    :param json_data: OpenAPI 3.0.1的JSON数据
    :return: 翻译后的JSON数据
    """
    if 'paths' in json_data:
        for url, methods in json_data['paths'].items():
            for method, details in methods.items():
                if 'summary' in details:
                    if details['summary'] == '更新授权用户所管理的组织资料':
                        print(1)
                    details['summary'] = translate_text(details['summary'], '一个api标题，注意首字母大写')
                if 'description' in details:
                    details['description'] = translate_text(details['description'], '一个api的描述')
                if 'parameters' in details:
                    for param in details['parameters']:
                        if 'description' in param:
                            param['description'] = translate_text(param['description'], 'api的一个参数的描述')
                if 'requestBody' in details and 'content' in details['requestBody']:
                    if 'application/json' in details['requestBody']['content']:
                        if 'schema' in details['requestBody']['content']['application/json']:
                            if 'properties' in details['requestBody']['content']['application/json']['schema']:
                                for param, prop in details['requestBody']['content']['application/json']['schema']['properties'].items():
                                    if 'description' in prop:
                                        prop['description'] = translate_text(prop['description'], 'api的一个参数的描述')
                                    if 'title' in prop:
                                        prop['title'] = translate_text(prop['title'], 'api的一个参数的描述')
                    if 'multipart/form-data' in details['requestBody']['content']:
                        if 'schema' in details['requestBody']['content']['multipart/form-data']:
                            if 'properties' in details['requestBody']['content']['multipart/form-data']['schema']:
                                for param, prop in details['requestBody']['content']['multipart/form-data']['schema'][
                                    'properties'].items():
                                    if 'description' in prop:
                                        prop['description'] = translate_text(prop['description'], 'api的一个参数的描述')
                                    if 'title' in prop:
                                        prop['title'] = translate_text(prop['title'], 'api的一个参数的描述')
                if 'responses' in details:
                    for status_code, response in details['responses'].items():
                        if 'description' in response:
                            response['description'] = translate_text(response['description'], 'api的一个响应的标题，注意首字母大写')
                        if 'content' in response and 'application/json' in response['content']:
                            if 'examples' in response['content']['application/json']:
                                for ex_name, example in response['content']['application/json']['examples'].items():
                                    if 'summary' in example:
                                        example['summary'] = translate_text(example['summary'], 'api的一个响应的标题，注意首字母大写')
                                    if 'value' in example:
                                        translate_response(example['value'])
                            if 'schema' in response['content']['application/json']:
                                translate_titles(response['content']['application/json']['schema'])


    return json_data


def init_cache():
    global cache
    # 初始化缓存
    cache = load_cache()
    r_cache = {
        ('仓库所属空间地址(组织或个人的地址path)', 'api的一个参数的描述'): "Repository space address (organization or individual's address path)",
        ('仓库所属空间地址(企业、组织 path)', 'api的一个参数的描述'): "Repository space address (enterprise or organization path)",
        ('组织名称', 'api的一个参数的描述'): "Organization Name",
        ('组织公开的邮箱地址', 'api的一个参数的描述'): "Organization's Public Email Address",
        ('组织所在地', 'api的一个参数的描述'): "Organization Location",
        ('组织简介', 'api的一个参数的描述'): "Organization Profile 或 Organization Description",
        ('组织站点', 'api的一个参数的描述'): "Organization Website",
        ('OpenHarmony是由开放原子开源基金会（OpenAtom Foundation）孵化及运营的开源项目，目标是面向全场景、全连接、全智能时代，搭建一个智能终端设备操作系统的框架和平台，促进万物互联产业的繁荣发展。', 'api的一个response的example的一个字段值'): "OpenHarmony is an open-source project incubated and operated by the OpenAtom Open Source Foundation. Its goal is to build an operating system framework and platform for the era of all-scenario, full-connectivity, and full-intelligence, promoting the prosperity and development of the万物互联industry.",
        ('yanfan是随时随地送达啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊实打实', 'api的一个response的example的一个字段值'): "abcabcabc",
        ('殿前都点检', 'api的一个response的example的一个字段值'): "abcabcabc",
    }
    for c in r_cache.keys():
        # 更新缓存
        cache[c] = r_cache[c]
        save_cache(cache)


def main():
    global client
    global cache
    client = OpenAI(
        api_key='your_api_key',
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    init_cache()
    # 读取OpenAPI JSON文
    with open('openapi_zh.json', 'r', encoding='utf-8') as file:
        openapi_data = json.load(file)

    # 翻译OpenAPI JSON数据
    translated_data = translate_openapi(openapi_data)

    # 保存翻译后的JSON文件
    with open('openapi_en.json', 'w', encoding='utf-8') as file:
        json.dump(translated_data, file, ensure_ascii=False, indent=4)

    user_input = input("是否保存缓存？(按 y 确认，其他键取消): ")
    if user_input.lower() == 'y':
        save_cache(cache)
    else:
        print("取消保存缓存。")

if __name__ == "__main__":
    main()